import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Box } from '@mui/material';
import ChatArea from './ChatArea';
import MenuBar from './MenuBar';
import { useWebSocket } from '../utils/WebSocketManager';
import ContactList from './ContactList';
import AddressBook from './AddressBook';
import Management from './Management';
import PluginList from './PluginList';
import MassSender from './MassSender';
import SchedulerInitializer from './SchedulerInitializer';
import { sendTextMessage, sendImageMessage } from '../services/messageService';
import { getContactInfo } from '../services/userService';
import { parse } from '../utils/WeChatMessageParser';
import { useUser } from '../contexts/UserContext';
import { dbService } from '../services/dbService';
import { API_CONFIG } from '../config/apiConfig';
import configService from '../services/configService';

const ChatRoom = () => {
  const [showAddressBook, setShowAddressBook] = useState(false);
  const [selectedPlugin, setSelectedPlugin] = useState(null);
  const [schedulerEnabled, setSchedulerEnabled] = useState(false);
  
  // 处理消息发送的函数引用，将传递给SchedulerInitializer组件
  const handleSendMessageRef = useRef(null);
  
  // 检查定时器是否启用
  useEffect(() => {
    const checkSchedulerSettings = async () => {
      try {
        await configService.initialize();
        const schedulerConfig = configService.getConfig('scheduler');
        setSchedulerEnabled(schedulerConfig?.enabled || false);
      } catch (error) {
        console.error('获取定时器配置失败:', error);
      }
    };
    
    checkSchedulerSettings();
  }, []);

  const { currentUser, updateContacts, contacts: dbContacts } = useUser();
  const currentUserRef = useRef(currentUser);
  const [contacts, setContacts] = useState({});

  // 从UserContext加载联系人数据
  useEffect(() => {
    if (dbContacts && Object.keys(dbContacts).length > 0) {
      setContacts(dbContacts);
    }
  }, [dbContacts]);

  useEffect(() => {
    currentUserRef.current = currentUser;
  }, [currentUser]);

  // 当contacts状态更新时，同步保存到IndexedDB
  // 使用防抖处理，避免频繁更新
  const updateContactsDebounced = useRef(null);

  useEffect(() => {
    if (Object.keys(contacts).length > 0) {
      // 清除之前的定时器
      if (updateContactsDebounced.current) {
        clearTimeout(updateContactsDebounced.current);
      }

      // 设置新的定时器，延迟300ms执行更新
      updateContactsDebounced.current = setTimeout(() => {
        updateContacts(contacts);
        console.log('联系人数据已同步到IndexedDB');
      }, 300);
    }

    return () => {
      if (updateContactsDebounced.current) {
        clearTimeout(updateContactsDebounced.current);
      }
    };
  }, [contacts, updateContacts]);
  // 消息状态管理
  const [messages, setMessages] = useState({});

  // 从IndexedDB加载消息记录
  useEffect(() => {
    const loadMessages = async () => {
      try {
        // 从IndexedDB获取消息记录
        const messagesRecord = await dbService.get(dbService.getStoreNames().MESSAGES, 'allMessages');
        if (messagesRecord && messagesRecord.data) {
          setMessages(messagesRecord.data);
          console.log('从IndexedDB加载消息记录成功');
        }
      } catch (error) {
        console.error('加载消息记录失败:', error);
      }
    };

    loadMessages();
  }, []);
  const [selectedContact, setSelectedContact] = useState('');
  const selectedContactRef = useRef(selectedContact);
  const [newMessage, setNewMessage] = useState('');


  useEffect(() => {
    selectedContactRef.current = selectedContact;
  }, [selectedContact]);



  useWebSocket(
    `${API_CONFIG.WS_HOST}/ws/GetSyncMsg?key=${API_CONFIG.KEY}`,
    async (message) => {
      console.log('收到消息:', message);
      const parsedMessage = parse(message);
      // 如果是群消息，更新发送人的信息
      if (parsedMessage.isGroupMessage) {
        const contactInfo = await getContactInfo(parsedMessage.actualSenderId);
        parsedMessage.senderName = contactInfo.name;
        parsedMessage.senderAvatar = contactInfo.avatar;
      }
      console.log('格式化消息：', parsedMessage);
      //获取或更新联系人信息
      const contactId = parsedMessage.senderId === currentUserRef.current.wxid && parsedMessage.senderId !== parsedMessage.recipientId
        ? parsedMessage.recipientId
        : parsedMessage.senderId;
      const contactInfo = await getContactInfo(contactId);
      parsedMessage.contractName = contactInfo.name;
      parsedMessage.contractAvatar = contactInfo.avatar;
      // 如果不是群消息，更新发送人的信息
      if(!parsedMessage.isGroupMessage){
        parsedMessage.senderName = contactInfo.name;
        parsedMessage.senderAvatar = contactInfo.avatar;
      }
      const lastmsg = lastMessageDisplay(parsedMessage);
      console.log(parsedMessage);
      // 更新联系人信息
      setContacts(prevContacts => {

        // 如果联系人已存在，只更新未读消息数和最新消息
        if (prevContacts[contactId]) {
          return {
            ...prevContacts,
            [contactId]: {
              ...prevContacts[contactId],
              lastMessage: lastmsg,
              timestamp: parsedMessage.timestamp,
              unread: contactId !== selectedContactRef.current ?
                ((prevContacts[contactId]?.unread || 0) + 1) : 0
            }
          };
        } else {
          // 联系人不存在时添加新联系人
          return {
            ...prevContacts,
            [contactId]: {
              id: contactId,
              name: parsedMessage.contractName || contactId.substring(0, 8),
              avatar: parsedMessage.contractAvatar || '',
              lastMessage: lastmsg,
              timestamp: parsedMessage.timestamp,
              unread: contactId !== selectedContactRef.current ? 1 : 0
            }
          };
        }
      });

      // 更新消息记录
      setMessages(prevMessages => {
        if (parsedMessage.senderId === currentUserRef.current.wxid) {
          parsedMessage.senderAvatar = currentUserRef.current.avatar;
        }

        let updatedMessages;
        // 如果是群消息直接更新
        if (parsedMessage.isGroupMessage) {
          // 使用群ID作为key，但显示实际发言人的信息
          updatedMessages = {
            ...prevMessages,
            [parsedMessage.senderId]: [...(prevMessages[parsedMessage.senderId] || []), {
              ...parsedMessage,
              displayName: parsedMessage.senderName,
              displayAvatar: parsedMessage.senderAvatar
            }]
          };
        }
        // 如果是私聊消息且发送人是currentUser且与接收人不同
        else if (parsedMessage.senderId === currentUserRef.current.wxid && parsedMessage.senderId !== parsedMessage.recipientId) {
          updatedMessages = {
            ...prevMessages,
            [parsedMessage.recipientId]: [...(prevMessages[parsedMessage.recipientId] || []), parsedMessage]
          };
        }
        // 其他情况正常更新
        else {
          updatedMessages = {
            ...prevMessages,
            [parsedMessage.senderId]: [...(prevMessages[parsedMessage.senderId] || []), parsedMessage]
          };
        }

        // 将更新后的消息保存到IndexedDB
        saveMessagesToStorage(updatedMessages);

        return updatedMessages;
      });
    }
  );


  // 处理消息发送 - 使用useCallback包装以避免不必要的重新创建
  const handleSendMessage = useCallback(async (messageObj, base64Image, updateLocalOnly = false, recipientId = null) => {

    if (!messageObj && newMessage.trim() === '') return;
    const messageId = messageObj ? messageObj.id : Date.now();
    
    // 只有在非图片消息或非更新模式时才设置newMessage
    if (!messageObj || (messageObj && messageObj.msgType !== 3)) {
      setNewMessage(messageObj ? messageObj.content : newMessage);
    }
    if(messageObj&&!messageObj.senderId){
      messageObj.senderId = currentUserRef.current.wxid;
      messageObj.senderName = currentUserRef.current.name;
      messageObj.senderAvatar = currentUserRef.current.avatar;
    }
    // 确定接收人ID，优先使用传入的recipientId（用于群发），否则使用当前选中的联系人
    const targetContactId = recipientId || selectedContact;
    
    const message = messageObj || {
      id: messageId,
      senderId: currentUser.wxid,
      senderName: currentUser.name,
      senderAvatar: currentUser.avatar,
      content: newMessage,
      timestamp: new Date().toISOString(),
      status: 'pending',
      msgType: 1,
      tag: "send",
      recipientId: targetContactId // 添加接收人ID
    };
    // 如果是更新已有消息（例如下载图片后更新内容）
    if (updateLocalOnly) {
      setMessages(prevMessages => {
        // 找到并更新指定的消息
        const updatedMessages = prevMessages[targetContactId]?.map(msg =>
          msg.id === message.id ? message : msg
        ) || [];

        const newMessages = {
          ...prevMessages,
          [targetContactId]: updatedMessages
        };
        // 保存到存储
        saveMessagesToStorage(newMessages);
        return newMessages;
      });
      return; // 不需要发送到服务器，直接返回
    }

    // 先更新本地聊天记录，显示待发送状态的消息
    setMessages(prevMessages => {
      const newMessages = {
        ...prevMessages,
        [targetContactId]: [...(prevMessages[targetContactId] || []), message]
      };
      // 保存到存储
      saveMessagesToStorage(newMessages);
      return newMessages;
    });

    // 更新联系人最后消息
    setContacts(prevContacts => {
      // 如果联系人不存在，则添加新联系人（针对群发场景）
      if (!prevContacts[targetContactId] && contacts[targetContactId]) {
        return {
          ...prevContacts,
          [targetContactId]: {
            ...contacts[targetContactId],
            lastMessage: message.msgType===3?'[图片消息]':message.content,
            timestamp: message.timestamp,
            unread: 0
          }
        };
      }
      
      return {
        ...prevContacts,
        [targetContactId]: {
          ...prevContacts[targetContactId],
          lastMessage: message.msgType===3?'[图片消息]':message.content,
          timestamp: message.timestamp,
          unread: 0
        }
      };
    });

    // 只有在非更新模式下才清空输入框
    if (!updateLocalOnly) {
      setNewMessage('');
    }

    // 异步发送消息并处理状态更新
    try {
      // 定义状态回调函数
      const statusCallback = (status) => {
        setMessages(prevMessages => {
          // 找到当前消息并更新其状态
          const updatedMessages = prevMessages[targetContactId]?.map(msg =>
            msg.id === messageId ? { ...msg, status } : msg
          ) || [];

          const newMessages = {
            ...prevMessages,
            [targetContactId]: updatedMessages
          };
          // 保存到存储
          saveMessagesToStorage(newMessages);
          return newMessages;
        });
      };
      if (message.msgType === 1) {
        await sendTextMessage(message.content || newMessage, targetContactId, statusCallback);
      } else {
        await sendImageMessage(base64Image, targetContactId, statusCallback);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      // 错误已在statusCallback中处理
    }
  }, [newMessage, selectedContact, currentUser, contacts, setMessages, setContacts, setNewMessage]);
  const lastMessageDisplay = (message) => {
    if (message.isGroupMessage) {
      return message.msgType === 3 ? `${message.senderName}:[图片消息]` : `${message.senderName}:${message.content}`;
    } else {
      return message.msgType === 3 ? `[图片消息]` : message.content
    }
  }
  // 处理联系人选择
  const handleSelectContact = (contactId) => {
    setSelectedContact(contactId);

    //将选中联系人的所有消息标记为已读并重置未读计数
    setMessages(prevMessages => {
      const updatedMessages = { ...prevMessages };
      if (updatedMessages[contactId]) {
        updatedMessages[contactId] = updatedMessages[contactId].map(message => {
          if (message.senderId !== currentUser.id) {
            return { ...message, read: true };
          }
          return message;
        });
      }
      // 保存到存储
      saveMessagesToStorage(updatedMessages);
      return updatedMessages;
    });

    // 重置未读计数
    setContacts(prevContacts => {
      return {
        ...prevContacts,
        [contactId]: {
          ...prevContacts[contactId],
          unread: 0
        }
      };
    });
  };

  const handleSelectFriend = (friend) => {
    setSelectedTab('message');
    setSelectedContact(friend.id);
    setContacts(prevContacts => {
      return {
        ...prevContacts,
        [friend.id]: {
          id: friend.id,
          name: friend.name,
          avatar: friend.avatar,
          timestamp: new Date().toISOString(),
          unread: 0
        }
      };
    });
  };
  // 消息存储辅助函数 - 使用防抖优化性能
  const saveMessagesDebounced = useRef(null);

  const saveMessagesToStorage = (messagesData) => {
    // 清除之前的定时器
    if (saveMessagesDebounced.current) {
      clearTimeout(saveMessagesDebounced.current);
    }

    // 设置新的定时器，延迟300ms执行保存
    saveMessagesDebounced.current = setTimeout(async () => {
      try {
        // 保存到IndexedDB
        await dbService.set(dbService.getStoreNames().MESSAGES, { id: 'allMessages', data: messagesData });
        console.log('消息数据已同步到IndexedDB');
      } catch (error) {
        console.error('保存消息数据失败:', error);
      }
    }, 300);
  };

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (saveMessagesDebounced.current) {
        clearTimeout(saveMessagesDebounced.current);
      }
    };
  }, []);

  // 获取当前聊天的消息
  const currentMessages = messages[selectedContact] || [];

  const [selectedTab, setSelectedTab] = useState('message');
  
  // 处理插件选择
  const handleSelectPlugin = (pluginId) => {
    setSelectedPlugin(pluginId);
  };
  
  // 重置插件选择
  const resetPluginSelection = () => {
    setSelectedPlugin(null);
  };
  
  // 当切换标签页时，重置插件选择
  useEffect(() => {
    if (selectedTab !== 'plugin') {
      resetPluginSelection();
    }
  }, [selectedTab]);

  // 在组件挂载时初始化handleSendMessage引用
  useEffect(() => {
    handleSendMessageRef.current = handleSendMessage;
  }, [handleSendMessage]);

  return (
    <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column', bgcolor: '#ececec', width: '100vw' }}>
      {/* 根据配置决定是否加载定时器服务 */}
      {schedulerEnabled && <SchedulerInitializer handleSendMessage={handleSendMessage}
      currentUser={currentUser} />}
      <Box sx={{ display: 'flex', flexGrow: 1, overflow: 'hidden', width: '100%' }}>
        <MenuBar selectedTab={selectedTab} setSelectedTab={setSelectedTab} showAddressBook={showAddressBook} setShowAddressBook={setShowAddressBook} />
        {/* 联系人列表、插件列表或管理界面 */}
        <Box sx={{ width: '320px', borderRight: '1px solid #d9d9d9' }}>
          {selectedTab === 'management' ? (
            <Management />
          ) : selectedTab === 'plugin' ? (
            <PluginList onSelectPlugin={handleSelectPlugin} />
          ) : (
            showAddressBook ? (
              <AddressBook
                onSelectFriend={handleSelectFriend}
                setShowAddressBook={setShowAddressBook}
              />
            ) : (
              <ContactList
                onSelectContact={handleSelectContact}
                selectedContactId={selectedContact}
                contacts={contacts}
              />
            )
          )}
        </Box>

        {/* 聊天区域或插件内容 */}
        {selectedTab === 'message' ? (
          <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <ChatArea
              messages={currentMessages}
              currentUser={currentUser}
              selectedContact={contacts[selectedContact]}
              newMessage={newMessage}
              setNewMessage={setNewMessage}
              handleSendMessage={handleSendMessage}
            />
          </Box>
        ) : selectedTab === 'plugin' && selectedPlugin === 'mass-sender' ? (
          <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <MassSender handleSendMessage={handleSendMessage} />
          </Box>
        ) : null}
      </Box>
    </Box>
  );
};

export default ChatRoom;